﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using hcom;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;

namespace hcms.Admin
{
	public partial class ArticleEdit : System.Web.UI.Page
	{
		public string submitstate;
		protected string editname;
		protected string cid;
		private hString hstr = new hString();
		public DataRowCollection posrows;
		public Model model = Global.model;
		protected void Page_Load(object sender, EventArgs e)
		{
			cid = Request["cid"];
			if( htmaid.Value == "" )	// 如果编辑框没有值，从命令行取。
				htmaid.Value = Request["aid"];

			//htmusetid.Value = model.getArtTemplate( htmaid.Value, cid ).ToString();	// 正在使用的模板，可能是栏目或系统指定的。

			posrows = model.getCurrentPos(cid);

			DataRowCollection rows;
			int n;
			if (!IsPostBack)
			{
				// 取所属栏目
				StringBuilder ids = new StringBuilder(1000);
				//StringBuilder names = new StringBuilder(1000);
				if (htmaid.Value == null || htmaid.Value == "")
				{
					DataRow row = model.getColumnByID(cid);
					ids.Append(cid);
					//names.Append(row["cname"]);
				}
				else
				{
					rows = model.getColumnsByAid(htmaid.Value);
					n = rows.Count;
					if (n > 0)
					{
						ids.Append(rows[0]["colID"]);
						//names.Append(rows[0]["cname"]);
					}
					for (int i = 1; i < n; i++)
					{
						ids.Append(",");
						ids.Append(rows[i]["colID"]);
						//names.Append(",");
						//names.Append(rows[0]["cname"]);
					}
				}
				htmcids.Value = ids.ToString();

				// 初始化文档模板下拉框
				ListItem li = new ListItem("", "0");
				idarttemplate.Items.Add(li);
				rows = model.getTemplateRows("a");
				n = rows.Count;
				for (int i = 0; i < n; i++)
				{
					DataRow row = rows[i];
					li = new ListItem(row["temName"].ToString(), row["temID"].ToString());
					idarttemplate.Items.Add(li);
				}

				if (htmaid.Value == null || htmaid.Value == "")
				{
					editname = "新建文档";

					idupdatetime.Value = DateTime.Now.ToString();
					iduser.Value = model.getNoteString("Username");	// 显示发布者名称
				}
				else
				{
					editname = "编辑文档";

					DataRow row = model.getArticleByID(htmaid.Value);
					idtitle.Value = row["artTitle"].ToString();
					//idkeyword.Value = row["keyword"].ToString();
					editor_id.Value = row["artContent"].ToString();
					idupdatetime.Value = row["artUpdateTime"].ToString();
					iduser.Value = row["userName"].ToString();	// 显示发布者名称
					idarttemplate.SelectedValue = row["artTemplateID"].ToString();
					idsource.Value = row["artSource"].ToString();	// 文章来源
					idlevel.Value = row["artLevel"].ToString();	// 文档级别，越大越靠前
					htmAssociate.Value = row["artAssociate"].ToString();	// 参考文档
					htmBrowserTitle.Value = row["artBrowserTitle"].ToString();	// 网页标题
				}
		
			}
			else
			{
				switch (cmd.Value)
				{
					case "save":
						save();
						break;
					default:
						throw (new Exception("不可识别的命令: \"" + cmd.Value + "\""));
				}

				editname = "编辑文档";
			}
	
		}

		private void save()
		{
			if (htmaid.Value == null || htmaid.Value == "")	// 创建新文档
			{
					// 保存文档
					string id = Guid.NewGuid().ToString();
					string strsql = string.Format("insert into hcms_Articles( artID, artTitle, " +
						"artContent, artUpdateTime, artUserID, artTemplateID, artSource, artLevel, artAssociate, artIP, artBrowserTitle) " +
						"values('{{{0}}}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}');",
						id,
						hstr.TrimToSQL(idtitle.Value),
						hstr.ToSQL(editor_id.Value),
						idupdatetime.Value,
						model.getNoteString("UserID"),	// 保存用户ID
						idarttemplate.SelectedValue,	// 文档选择的模板
						hstr.TrimToSQL(idsource.Value),
						hstr.TrimToSQL(idlevel.Value),
						getAssociate(),
						Request.ServerVariables["REMOTE_ADDR"],
						hstr.TrimToSQL(htmBrowserTitle.Value)
						);
					model.da.Execute(strsql);
					htmaid.Value = id;
			}
			else
			{
				string strsql = string.Format("UPDATE hcms_Articles SET artTitle='{0}', " +
					"artContent='{1}', artUpdateTime='{2}', artTemplateID='{4}', " +
					"artSource='{5}', artLevel='{6}', artAssociate='{7}', artIP='{8}', artBrowserTitle='{9}' " +
					" WHERE artID = '{10}'",
					hstr.TrimToSQL(idtitle.Value),
					hstr.ToSQL(editor_id.Value),
					idupdatetime.Value,
					0, //hstr.ToSQL(idauthor.Value),	// 不更新作者
					idarttemplate.SelectedValue,
					hstr.TrimToSQL(idsource.Value),
					hstr.TrimToSQL(idlevel.Value),
					getAssociate(),
					Request.ServerVariables["REMOTE_ADDR"],
					hstr.TrimToSQL(htmBrowserTitle.Value),
					htmaid.Value
					);
				model.da.Execute(strsql);

				model.delFiles(htmaid.Value); // 删除所有静态文档，有可能多个栏目包括该文档。
			}

			// 保存文档对应的栏目，可能是多个栏目。保存文档模板，便于打开文档时直接查找对应的模板
			model.saveArticleCids(htmaid.Value, htmcids.Value);

			submitstate = "保存完毕";
		}

		// 取参考文档并格式化("id1\nid2\nid3..."), ##最多取20个
		private string getAssociate()
		{
			StringBuilder str = new StringBuilder( 1000 );
			//"004-59779bb8-6bf5-4b95-a302-d41f0d1bea75-18.htm"
			Regex r = new Regex( @"(\d+-\w{8}-\w{4}-\w{4}-\w{4}-\w{12})" );
			MatchCollection matchCollection = r.Matches(htmAssociate.Value);
			int n = matchCollection.Count;
			if( n > 20 )
				n = 20;
			for( int i = 0; i < n; i++ )
			{
				Match m = matchCollection[i];
				str.Append( m.Result("$1\n") );
			}
			if( str.Length > 0 )
				str.Length--;		// 去掉最后一个换行符。

			htmAssociate.Value = str.ToString();
			return htmAssociate.Value;
		}

	}
}